import { isEmpty } from './utils'

const baseUrl = import.meta.env.VITE_APP_URL
// const env = import.meta.env.VITE_APP_ENV

// 响应参数
interface Response<T = any> {
  code: number
  data: T extends any ? T : any
  message?: string
}
// 请求拦截器
const requestInterceptor = (params: netWork): netWork => {
  const config = {
    url: baseUrl + params.url,
    data: params.data,
    method: params.method,
    header: params.header
  }
  if (!isEmpty(params.data)) {
    config.data = params.data
  }
  return config
}

// 响应拦截器
const responseInterceptor = <T>(res: Response): Result<T> | undefined => {
  if (res.code === 200) {
    if (typeof res === 'object' && 'code' in res) {
      return res
    } else {
      const ans = {
        code: 100,
        data: res.data as T,
        message: '返回值错误'
      }
      return ans
    }
  } else {
    uni.showToast({
      title: res?.message || '请求失败',
      icon: 'error'
    })
    return undefined
  }
}

/**
 * @description: 网络请求
 * @param {netWork} params
 * @return {Promise}
 */
const request = (params: netWork): Promise<Response> => {
  const config = requestInterceptor(params)
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (res) => {
        const ans = res.data as Response
        resolve(responseInterceptor(ans))
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

class Request {
  //  get请求，使用泛型封装
  public get<T>(url: string, data?: object): Promise<Response<T>> {
    return request({ url, data, method: 'GET' })
  }
  //  post请求，使用泛型封装
  public post<T>(url: string, data?: object): Promise<Response<T>> {
    return request({
      url,
      data,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      }
    })
  }

  public getToken<T>(
    url: string,
    data?: object,
    token?: string
  ): Promise<Response<T>> {
    return request({
      url,
      data,
      method: 'GET',
      header: {
        Authorization: `Bearer ${token}`
      }
    })
  }

  public postToken<T>(
    url: string,
    data?: object,
    token?: string
  ): Promise<Response<T>> {
    return request({
      url,
      data,
      method: 'POST',
      header: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  public postTokenNotImg<T>(
    url: string,
    data?: object,
    token?: string
  ): Promise<Response<T>> {
    return request({
      url,
      data,
      method: 'POST',
      header: {
        Authorization: `Bearer ${token}`
      }
    })
  }

  public postTokenHead<T>(
    url: string,
    data?: object,
    token?: string
  ): Promise<Response<T>> {
    return request({
      url,
      data,
      method: 'POST',
      header: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      }
    })
  }
}
export default new Request()
